<template>
  <div id="app">
    <h1>Vue中axios拦截器的使用</h1>
    <button @click="handleClick">按钮</button>
    <div v-if="loading">loading...</div>
    <p v-else>{{ title }}</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      title: '',
      // 未加载
      loading: false
    }
  },
  methods: {
    handleClick() {
      axios.get('https://jsonplaceholder.typicode.com/todos/1').then((res) => {
        this.title = res.data.title;
      });
    },
  },
  created() {
    axios.interceptors.request.use((config) => {
      // 请求拦截
      this.loading = true;
      return config;
    })

    axios.interceptors.response.use((config) => {
      // 响应拦截
      this.loading = false; // 请求完毕
      return config;
    })
  }
};
</script>

<style>
#app {
  text-align: center;
}
</style>
